// 实时监控
<template>
  <f7-page class="detail">
    <f7-navbar>
      <f7-nav-left>
        <f7-link back icon-material="arrow_back"></f7-link>
      </f7-nav-left>
      <f7-nav-title>实时监控</f7-nav-title>
      <f7-nav-right></f7-nav-right>
    </f7-navbar>
    <f7-block>
      <div class="header-div">
        <img v-if="equipmentType" :src="require(`@/assets/img/hoisting/${equipmentType}_icon.png`)" alt="" />
        <div class="content-box">
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <p>{{equipInfo.propertyCode||title}}</p>
            <div v-if="videoData.videoId" style="display: flex; align-items: center;">
              <span class="tag tag-green">{{ videoData.state === 1 ? '在线' : '离线' }}</span>
              <img @click="playVideo" src="@/assets/img/qzjx/detail-icon1.png" style="width: 32px; margin: 0 0 0 10px;">
            </div>
          </div>
          <p v-if="equipInfo.craneTypeName">
            <span class="tag tag-fill">{{equipInfo.craneTypeName||'--'}}</span>
            <!-- <span class="tag tag-fill">自编号：{{equipInfo.propertyCode}}</span> -->
          </p>
          <p>用于工程：{{equipInfo.engineeName||'--'}}</p>
        </div>
      </div>
      <div class="real-monitor">
        <div class="title-box">
          <h3>实时监测</h3>
          <span class="tag tag-green">{{equipInfo.state==1?'在线':'离线'}}</span>
        </div>
        <van-swipe @change="onChange" ref="qzjxSwipe" :loop="true" :touchable="false" v-if="equipmentType" >
          <van-swipe-item v-for="(item,index) in cranebox" :key="index">
            <div class="content-box">
              <ul>
                <li v-for="item in machineInfo" :key="item.key">
                  <img :src="require(`@/assets/img/hoisting/${equipmentType}_${item.key}.png`)" alt="" />
                  <p>
                    <span v-if="item.key!='isDoorB'&&item.key!='isDoorF'">{{ model[item.key]==null?'--':model[item.key]}} <i>{{item.unit}}</i></span>
                    <span v-else style="font-size: 15px;">{{ model[item.key]==null?'--':model[item.key]==0?'关闭':'打开'}}</span>
                    <span>{{item.label}}</span>
                  </p>
                </li>
              </ul>
              <div class="content-bottom">
                <div class="left-box">终端</div>
                <div class="right-box">
                  <h3>{{equipInfo.terminalCode||'--'}}</h3>
                  <p>接入标准：{{equipInfo.accessStandards==null?'--':equipInfo.accessStandards=='old'?'旧国标':'新国标'}}</p>
                  <p>接入IP：{{equipInfo.ipAddress || '--'}}</p>
                  <!-- <p>Mac地址：{{equipInfo.macAddress || '--'}}</p> -->
                  <p>最新监测时间：{{equipInfo.runTime || '--'}}</p>
                </div>
              </div>
            </div>
          </van-swipe-item>
          <template #indicator>
            <div class="custom-indicator">
              <template v-if="cranebox.length>1">
                <div class="dot left" v-show="currentIndex>0">
                    <van-icon name="arrow-left" @click="goNext('prev',0)" />
                </div>
                <div class="dot right" v-show="currentIndex!=cranebox.length-1">
                    <van-icon name="arrow" @click="goNext('next',1)" />
                </div>
              </template>
            </div>
          </template>
        </van-swipe>
      </div>
      <!-- <div class="facility" v-if="$f7route.query.equipmentType=='TSQZJ'">
        <div class="title-box">
          <h3>实时监测</h3>
          <span class="tag tag-green">{{videoStatus=='1'?'在线':'离线'}}</span>
        </div>
        <div class="content-box">
          <div class="video">
            <img :src="imgPic" alt="" v-if="imgPic">
            <div v-else style="text-align: center;line-height:176px;font-size: 14px;color: #aaa4a4;">暂无监控画面</div>
            <img class="videoPlan" v-if="videoUrl" src="../../../../assets/img/hoisting/video.svg" alt="" @click="openVideo">
          </div>
        </div>
      </div> -->
    </f7-block>
  </f7-page>
</template>

<script>
import Config from "@/libs/config";
import Controller from "@/libs/framework/controller";
export default class sInsp extends Controller {
  onBeforeInit() {
    this.urls = {
      model:  ["/app/crane/monitor/getStaticInfo","","/crane/videoApplication/getMobileVideoParam"]
    };
  }
  onInit() {
    this.context.equipmentType=this.$params.equipmentType
    if(this.$params.equeId) {
      if(this.$params.equipmentType=='SGSJJ'){
        this.urls.model[1]='/app/crane/monitor/getSgsjjRealTimeInfo'
      } else {
        this.urls.model[1]='/app/crane/monitor/getTdRealTimeInfo'
      }
    } else {
      this.urls.model[1]=''
    }
    this.context.machineInfo=this.context[`machineInfo${this.$params.equipmentType}`]
    this.context.title = this.$params.propertyCode;
    this.context.equeId=null
    this.context.currentIndex=0
  }
  onBeforeQuery(type, conditions, params) {
    this.vm.$f7.preloader.show()
    // params.equeId = '91340104MA2RH0796ETC2023050473';
    params.equeId = this.context.equeId||this.$params.equeId;
  }
  onAfterQuery(type, isSuccess, result) {
    if (!result.success) {
        setTimeout(() => {
            this.vm.$f7.preloader.hide()
            this.vm.$f7.dialog.alert(result.message||'数据加载失败，请刷新页面重试')
        }, 3000)
    }
    if(type=='form') {
      for (let item in this.context.equipInfo) {
        this.context.equipInfo[item] = result.parameters.equipmentInfo[item]
      }
      this.context.equipmentType=result.parameters.equipmentInfo.craneType
      this.context.video=result.parameters.video || {}
      this.context.machineInfo=this.context[`machineInfo${this.context.equipmentType}`]
    } else if(type=='form$1') {
      this.context.model = result.parameters.equipRealTimeInfo;
      this.context.equipInfo.runTime=result.parameters.equipRealTimeInfo.runTime
      this.context.cranebox=result.parameters.cranebox
    } else if(type=='form$2') {
      const { videos, umsdkParam } = result.parameters
      if (videos && videos.length) {
        const video = videos[videos.length - 1]
        this.context.videoData = {
          ...umsdkParam,
          videoId: video.videoCode,
          state: video.state
        }
      }
    }
    return result;
  }

  mixin() {
    return {
      props: {},
      components: {},
      data() {
        return {
          cranebox:[],
          equipmentType:'',
          title: "",
          model: {},
          equipInfo:{
            engineeName: '',// 工程名称
            craneTypeName: "", // 设备类型
            propertyCode: '',// 设备编号
            terminalCode: "", // 黑匣子编号
            accessStandards: '', // 接入标准,
            runTime: "", //监测时间
            ipAddress: "", // 接入ip地址
            macAddress: "", // 接入mac地址
            isBan: true, // 被禁止
            state: 0, // 在线状态
          },
          machineInfo:[],
          machineInfoTSQZJ:[
            {label:'力矩',key:'moment',unit:'%'},
            {label:'幅度',key:'range',unit:'m'},
            {label:'载重',key:'weight',unit:'t'},
            {label:'高度',key:'height',unit:'m'},
            {label:'吊绳倍率',key:'multiplyingPower',unit:''},
            {label:'回转角度',key:'gyration',unit:'°'},
            {label:'风速',key:'windSpeed',unit:'m/s'},
            {label:'塔身倾斜角度',key:'dip',unit:'°'},
          ],
          machineInfoSGSJJ:[
            {label:'载重',key:'weight',unit:'t'},
            {label:'前门',key:'isDoorF',unit:''},
            {label:'高度',key:'height',unit:'m'},
            {label:'后门',key:'isDoorB',unit:''},
            {label:'速度',key:'speed',unit:'m/s'},
          ],
          playUrl: null,
          videoPlayerTimer: null,
          timeId:null,
          imgPic:null,
          videoUrl:'',
          videoStatus:"",
          currentIndex:0,
          equeId:null,
          // 监控视频对象
          videoData: {}
        };
      },
      computed: {},
      methods: {
        // 视频播放
        playVideo(){
          if(this.$util.isUmSdk()) {
            // 加个loading
            this.$f7.preloader.show()
            umSdk.callHandler(
              'openDaHuaPreVideo',
              {
                'videoServer': this.videoData.videoServer,
                'videoPort': this.videoData.videoPort,
                'videoUser': this.videoData.videoUser,
                'videoPasscode': this.videoData.videoPasscode,
                'videoChannelId': this.videoData.videoId
              },
              () => {
                this.$f7.preloader.hide()
              }
            )
          }
        },
        goNext(method){
          this.$refs.qzjxSwipe[method]()
          if(method=='prev'){
            this.currentIndex--
          }else{
            this.currentIndex++
          }
        },
        onChange(index){
          // if (index >= this.cranebox.length) {
          //   this.currentIndex = 0;
          // } else {
          //   this.currentIndex = index;
          // }
          // this.currentIndex=index
          this.equeId=this.cranebox[this.currentIndex].equeId
          this.searchQuery({},'form$1')
          this.searchQuery({},'form')
        },
        async getVideoUrl(){
          this.videoUrl=""
          const res=await this.$util.getPromise(`/mobileApi/crane/videoApplication/getUmSdkVideoUrl?propertyCode=${this.$f7route.query.propertyCode}`)
          const {DataContext} = res
          this.videoUrl=DataContext
        },
        async getVideoStatus(){
          this.videoStatus=""
          const res=await this.$util.getPromise(`/app/crane/videoApplication/getVideoOnlineStatus?propertyCode=${this.$f7route.query.propertyCode}`)
          const {parameters} = res
          this.videoStatus=parameters.isOnline
        },
        openVideo(){
          if (umSdk && umSdk.status == 'ready') {

            // let url=`${Config.api.server}/mobileApi/crane/videoApplication/getUmSdkVideoUrl?propertyCode=${this.$f7route.query.propertyCode}`
            umSdk.ivmsplayv2({
                //获取视频流预览链接接口，摄像头参数的videoUrl地址前缀+/openapi/video/hkisc/previewurls
                apiaddress: this.videoUrl,
                postdata: {},
                success: function (r) {

                },
                fail: function (e) {

                }
            });
          }
        },
        // 设置定时器,5分钟后停止播放
        setCloseVideoPlayInterval() {
          this.videoPlayerTimer && clearInterval(this.videoPlayerTimer)
          this.videoPlayerTimer = setInterval(() => {
            this.$refs.dhplayerRef.closeVideo();
          }, 300000);
        },
        async clickWindow(snum, info) {
          if (info) {
            this.$refs.dhplayerRef.closeVideo();
          } else {
            this.createSuccess()
          }
        },
        realSuccess(info) {// 返回通道信息
          console.log("实时预览成功", info)
          this.$f7.dialog.toast('司机室监控画面每五分钟会自动停止播放！');
        },
        realError(info, err) { // 放回通道信息和错误提示
          console.log("实时预览失败", info)
        },
        async createSuccess() {
          let params = {
            propertyCode: this.$f7route.query.propertyCode || "",
          }
          const res=await this.$util.getPromise('/app/crane/videoApplication/getVideoUrl', params)
          const {success, parameters} = res || {};
          if (success) {
            this.playUrl = parameters.playUrl;
            this.$refs.dhplayerRef.realByUrl({
              channelId: '1021127$1$0$0', // 通道id
              path: this.playUrl,
              redirect: false, // 9090端口为true   9100端口为false 必传
              camerType: '2' // 1-软解 2-硬解 可不传
            }, 0) // 播放的窗口序号 (从0开始计数，表示第一个窗口)
            this.setCloseVideoPlayInterval();
          }
        },
        createError(err) {
          if ((err.code == 1001 || err.info === '插件未安装!') && this.tipCount == 0) {
            this.$confirm("您当前暂未安装视频插件，无法观看司机室监控画面，是否安装？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              let url = '/cranesystem/static/video/PlayerSetup.exe';
              const a = document.createElement('a')
              a.href = url
              a.download = 'PlayerSetup.exe' // 下载后文件名
              a.style.display = 'none'
              document.body.appendChild(a)
              a.click() // 点击下载
              document.body.removeChild(a) // 下载完成移除元素
            });
            this.tipCount++;
          }
        },
        getPic(){
          this.$f7.request.post(
              `/app/crane/videoApplication/getCoverUrl?propertyCode=${this.$f7route.query.propertyCode}`,
              {},
              rlt => {
                  this.imgPic=rlt
              },
              rlt => {
                  rlt.message = "获取数据失败，请稍后重试";
                  this.$f7.dialog.toast(rlt.message)
              }
          );
        },
      },
      created() {
        if(this.equipmentType=='TSQZJ'){
          // this.getPic()
          // this.getVideoUrl()
          // this.getVideoStatus()
        }
      },
      mounted() {
        this.timeId&&clearInterval(this.timeId)
        // 每30秒更新一次数据
        // 如果没有equeId就不开启定时刷新了
        if(this.equeId) {
          this.timeId = setInterval(() => {
            this.searchQuery({},'form$1')
          }, 30000);
        }
      },
      beforeDestroy() {
        console.log('beforeDestroy-----');
        clearInterval(this.timeId);
      },
      watch: {
        currentIndex(val){
          console.log(val,1111);
        }
      },
    };
  }
}
</script>

<style lang="less" scoped>
@import url("./common.less");
.video{
  height: 176px;
  background: #F5F7FA;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  img{
    width: 100%;
    height: 100%;
  }
  .videoPlan{
    width: 45px;
    height: 45px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
  }
}
.custom-indicator{
  .dot{
    width: 30px;
    height: 30px;
    background: #cccccc80;
    color: #ffff;
    border-radius: 30px;
    text-align: center;
    line-height: 33px;
    position: absolute;
    z-index: 999999999;
    top: 50%;
    transform: translateY(-50%);
    &.left{
      left: 10px;
    }
    &.right{
      right: 10px;
    }
  }
}
</style>
